<?php

namespace app\common\model;

use think\Loader;
use think\Model;
use think\Session;
use think\Validate;

class User extends Model
{
    //连接数据库
    protected $table= 'user';
    protected $pk= 'uid';
    //登录
    public function login($data){
        $vailDate =Loader::validate('user');
        if(!$vailDate->check($data)){
            return['valid'=>0,'msg'=>$vailDate->getError()];
       }
        //登录判断
        $userInfo=$this->where('username',$data['username'])->where('password',md5($data['password']))->find();
        if(!$userInfo){
            return['valid'=>0,'msg'=>'用户名或密码错误'];
        }
        //3.登录成功
        session('admin.username',$userInfo['username']);
        session('admin.uid',$userInfo['uid']);
        return ['valid'=>1,'msg'=>'登录成功'];
    }
    //修改密码
    public function edit($data){
        //1.手册搜索验证器 进行验证
        $validate = Loader::validate('EditPsw');
        if(!$validate->check($data)){
            return ['valid'=>0,'msg'=>$validate->getError()];
        }

        //2.判断输入的原密码是否正确
        $userInfo = $this->where('uid',session('admin.uid'))->find();
        if($userInfo['password'] != md5($data['password'])){
            return ['valid'=>0,'msg'=>'旧密码错误'];
        }

        //3.修改密码
        $res = $this->save([
            'password'  => md5($data['new_password']),
        ],[$this->pk => $userInfo['uid']]);
        if ($res){
            Session::delete('admin');
            return ['valid'=>1,'msg'=>'修改成功'];
        }else{
            return ['valid'=>0,'msg'=>'修改失败'];
        }
    }

}